//
//  PhotoDetailViewController.m
//  XPhoto
//
//  Created by baboy on 2019/7/2.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "PostDetailViewController.h"
#import "BKCommentView.h"
#import "PhotoTableViewCell.h"
#import "CommentCell.h"
#import "UIButton+x.h"
#import "BKIndicator.h"
#import "PostAction.h"
#import "SerialPostDetailViewController.h"
#import "UserProfileViewController.h"
#import "BKNavigationController.h"
#import <AFNetworking/UIButton+AFNetworking.h>

@interface PostDetailViewController ()<PhotoTableViewCellDelegate,BKCommentViewDelegate, CommentCellDelegate>
@property(nonatomic, strong) NSMutableArray<Comment*> *comments;
@property(nonatomic, strong) CommentSearchArgs *searchArgs;
@end

@implementation PostDetailViewController
- (id)init{
    if (self = [super initWithNibName:NSStringFromClass([self class]) bundle:nil]){
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
                                              initWithTitle:NSLocalizedString(@"share", @"按钮")
                                              style:UIBarButtonItemStyleDone
                                              target:self
                                              action:@selector(share:)];
    [self.avatarButton setImageForState:UIControlStateNormal withURL:[NSURL URLWithString:[[User currentUser] avatarThumb]]];
    self.commentView = [BKCommentView view];
    self.commentView.delegate = self;
    
    self.searchArgs = [CommentSearchArgs new];
    self.searchArgs.postId = self.post.id;
    self.searchArgs.refId = 0;
    [self searchCommentWithArgs:self.searchArgs];
    // Do any additional setup after loading the view from its nib.
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    [self.commentView layoutSubviewsWithKeyboardPopup:NO];
}
- (void)searchCommentWithArgs:(CommentSearchArgs *)args{
    [Comment searchWithArgs:args
                   callback:^(id  task, id comments, NSError * error) {
        if (error) {
            [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
            return;
        }
        if (args.maxId == 0) {
            self.comments = [NSMutableArray array];
        }
        [self.comments addObjectsFromArray:comments];
        [self.tableView reloadSections:[[NSIndexSet alloc] initWithIndex:1] withRowAnimation:UITableViewRowAnimationAutomatic];
    }];
}
/**
 * 根据索引获取评论
 */
- (NSIndexPath *)commentIndexPathAtIndex:(NSUInteger)index{
    NSInteger j = 0;
    for (NSInteger i = 0, n = self.comments.count; i < n; i++) {
        Comment *comment = [self.comments objectAtIndex:i];
        if (j == index) {
            return [NSIndexPath indexPathForRow:0 inSection:i];
        }
        j += 1;
        if ( comment.replyComments &&  ( index -j ) < comment.replyComments.count ) {
            return [NSIndexPath indexPathForRow:index - (j-1) inSection:i];
        }
        j += comment.replyComments ? comment.replyComments.count : 0;
    }
    return nil;
}
- (Comment *)commentAtIndex:(NSUInteger)index{
    NSIndexPath *commentIndexPath = [self commentIndexPathAtIndex:index];
    Comment *rootComment = [self.comments objectAtIndex:commentIndexPath.section];
    Comment *comment = rootComment;
    if (commentIndexPath.row > 0) {
        comment = [comment.replyComments objectAtIndex:commentIndexPath.row -1];
        comment.ref = comment.ref ?: rootComment;
    }
    return comment;
}
- (NSInteger) numOfComments{
    NSInteger n = 0;
    for (Comment *comment in self.comments) {
        n += 1;
        n += comment.replyComments ? comment.replyComments.count : 0;
    }
    return n;
}
- (void)loadMore:(BKTableView *)tableView{
    if (self.comments.count>0) {
        self.searchArgs.maxId = self.comments.lastObject.id;
    }
    [self searchCommentWithArgs:self.searchArgs];
}
- (IBAction)addComment:(id)sender{
    [self.commentView show];
}
- (IBAction)sendComment:(id)sender{
    self.commentView.textView.text = nil;
    [self.commentView.textView resignFirstResponder];
}
- (IBAction)like:(id)sender{    
    PostAction *action = [PostAction new];
    action.postId = self.post.id;
    
    [BKIndicator showMessage:NSLocalizedString(@"add_like_now", @"提示")];
    [PostAction addLike:action
                callback:^(id  _Nonnull task, id  _Nullable json, NSError * _Nullable error) {
                    if (error) {
                        [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
                        return;
                    }
                    [BKIndicator showMessageAndFadeOut:NSLocalizedString(@"add_success", @"提示") completion:nil];
                }];
}
- (IBAction)share:(id)sender{
    PostAction *action = [PostAction new];
    action.postId = self.post.id;
    
    [PostAction addShare:action
                 callback:^(id  _Nonnull task, id  _Nullable json, NSError * _Nullable error) {
                 }];
}
- (IBAction)fav:(id)sender{
    
    PostAction *action = [PostAction new];
    action.postId = self.post.id;
    
    [BKIndicator showMessage:NSLocalizedString(@"add_favorite_now", @"提示")];
    [PostAction addFav:action
               callback:^(id  _Nonnull task, id  _Nullable json, NSError * _Nullable error) {
                   if (error) {
                       [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
                       return;
                   }
                   [BKIndicator showMessageAndFadeOut:NSLocalizedString(@"add_success", @"提示") completion:nil];
               }];
}
#pragma UITableView delegate
- (CommentCell *)commentCell{
    static NSString *CELL_ID = @"CommentCell";
    CommentCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CELL_ID];
    if (!cell) {
        cell = loadViewFromNib([CommentCell class], self);
        cell.delegate = self;
    }
    return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    return [self numOfComments];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
     return UITableViewAutomaticDimension;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        PhotoTableViewCell *cell = [self photoTableViewCellForTableView:tableView];
        cell.style = PhotoTableViewCellStyleNoAction;
        cell.post = self.post;
        return cell;
    }
    NSIndexPath *commentIndexPath = [self commentIndexPathAtIndex:indexPath.row];
    Comment *rootComment = [self.comments objectAtIndex:commentIndexPath.section];
    Comment *comment = rootComment;
    if (commentIndexPath.row > 0) {
        comment = [comment.replyComments objectAtIndex:commentIndexPath.row -1];
    }
    CommentCell *commentCell = [self commentCell];
    commentCell.comment = comment;
    commentCell.hasMore = commentIndexPath.row == rootComment.replyComments.count && rootComment.replyCount > rootComment.replyComments.count;
    return commentCell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        
        Comment *comment = [self commentAtIndex:indexPath.row];
        [self replyToComment:comment];
    }
}
-(NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 1){
        Comment *comment = [self commentAtIndex:indexPath.row];
        if (comment.refId > 0) {
            return 2;
        }
    }
    return 0;
}
#pragma CommentCell Delegate
- (void)replyToComment:(Comment *)comment{
    NSString *text = [NSString stringWithFormat:@"@%@ ", comment.user.userName];
    self.commentView.userInfo = comment;
    [self.commentView showWithText:text];
}
- (void)openUserProfileViewController:(NSInteger)uid{
    UserProfileViewController *vc = [UserProfileViewController new];
    vc.uid = uid;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)commentCellDidClickAvatar:(CommentCell *)commentCell{
    Comment *comment = [commentCell comment];
    [self openUserProfileViewController:comment.uid];
}
- (void)commentCellDidClickNickname:(CommentCell *)commentCell{
    Comment *comment = [commentCell comment];
    [self openUserProfileViewController:comment.uid];
}

- (void)commentCellDidClickMoreButton:(CommentCell *)commentCell{
    Comment *comment = [commentCell comment];
    CommentSearchArgs *args = [CommentSearchArgs new];
    args.postId = comment.postId;
    args.refId = comment.id;
    
    [Comment searchWithArgs:args
                   callback:^(id  task, NSArray *comments, NSError * error) {
        if (error) {
            [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
            return;
        }
        NSMutableArray *arr = [NSMutableArray arrayWithArray:comment.replyComments];
        [arr addObjectsFromArray:comments];
        comment.replyComments = arr;
        
        [self.tableView reloadData];
    }];
}
//- (void)commentCellDidClickContent:(CommentCell *)commentCell{
//    Comment *comment = [commentCell comment];
//}
//- (void)commentCellDidClickReply:(CommentCell*)commentCell{
//    Comment *comment = [commentCell comment];
//    NSString *text = [NSString stringWithFormat:@"@%@ ", comment.user.userName];
//    [self.commentView showWithText:text];
//}

#pragma BKCommentViewDelegate
- (BOOL)textViewShouldEndEditing:(BKCommentView *)commentView{
    commentView.userInfo = nil;
    return YES;
}
- (void)commentView:(BKCommentView*)view didClickedSendButton:(id)button{
    NSString *content = [view.textView.text?:@"" stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (!content || content.length == 0) {
        [BKIndicator showMessageAndFadeOut:NSLocalizedString(@"serial_no_published", @"提示") completion:nil];
        return;
    }
    Comment *replyTo = view.userInfo;
    
    Comment *comment = [Comment new];
    comment.content = content;
    comment.postId = self.post.id;
    if (replyTo) {
        comment.refId = replyTo.refId > 0 ? replyTo.refId : replyTo.id;
        comment.replyTo = replyTo.id;
    }
    
    [BKIndicator showMessage:NSLocalizedString(@"submitting", @"提示")];
    [Comment add:comment
        callback:^(id  _Nonnull task, id  _Nullable json, NSError * _Nullable error) {
        if (error) {
            [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
            return;
        }
        view.textView.text = nil;
        [BKIndicator showMessageAndFadeOut:NSLocalizedString(@"submit_success", @"提示") completion:nil];
        self.searchArgs.maxId = 0;
        [self searchCommentWithArgs:self.searchArgs];
    }];
}
- (void)photoTableViewCell:(id)photoTableViewCell openLink:(NSURL *)url{
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
